package com.it.tydic.estate.common.exception;

import com.it.tydic.estate.common.aop.CodeMsg;
import com.it.tydic.estate.common.aop.Result;
import com.sun.org.apache.regexp.internal.RE;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 通用错误一般用于 catch 抛出异常的时候 详情见消息体
     */
    public static final Integer GENERAL_ERROR = 604;

    //处理通用异常
    @ExceptionHandler(value = Exception.class)
    public Result defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        StackTraceElement[] stackTrace = e.getStackTrace();
        StringBuilder sb = new StringBuilder("[系统错误！" + e.getClass().getName() + ": " + e.getLocalizedMessage() + "]\n");
        for (StackTraceElement stackTraceElement : e.getStackTrace()) {
            String s = stackTraceElement.toString();
            if (s.startsWith("com.it.tydic.estate.module")) {
                sb.append(s).append("\n");
            }
        }
        System.out.println(sb.toString());
        CodeMsg codeMsg=new CodeMsg(500,sb.toString());
        return  Result.error(codeMsg);
    }

    @ExceptionHandler(CustomException.class)//可以将Exception中的异常信息以Json的信息返回给前端
    public Result handle(CustomException e) {
        logger.error("状态码:" + e.getErrorCode(), e);
        return this.error(e);
    }

    public static Result error(CustomException e) {
        System.out.println(e.getErrorCode()+"-----"+e.getMessage());
        CodeMsg codeMsg=new CodeMsg(e.getErrorCode(),"cuwu");


        return  Result.error(codeMsg);
    }

}


